package org.jiamandan.com.config;


import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jiamandan.com.service.IRechargeGunService;
import org.jiamandan.com.service.IRechargePileService;
import org.jiamandan.com.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.jiamandan.com.cache.CacheNames;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class UdpDeviceCleanupTask {
    @Autowired
    private RedisUtil redisUtil;
    private static final long TIMEOUT = 300_000; // 5 分钟

    @Scheduled(fixedRate = 60_000) // 每分钟执行一次
    public void cleanupInactiveDevices() {
        Map<Object, Object> allDevices = redisUtil.hmget(CacheNames.DEVICE_STATUS_CACHE_KEY);
        long currentTime = System.currentTimeMillis();
        allDevices.forEach((deviceNo, json) -> {
            Map<Object, Object> status = JSON.parseObject(JSONObject.toJSONString(json), Map.class);
            long lastActive = (Long) status.get("lastActive");
            if (currentTime - lastActive > TIMEOUT) {
                // 清理超时设备
                redisUtil.hdel(CacheNames.DEVICE_STATUS_CACHE_KEY, deviceNo);
                log.info("设备 {} 因超时被清理, 最后活跃时间: {}", deviceNo, DateFormatUtils.format(new Date(lastActive),"yyyy-MM-dd HH:mm:ss"));
                //设备离线
                handlerPileOffline(deviceNo.toString());
            }
        });
    }

    /**
     * 设备离线设置
     */
    private void handlerPileOffline(String pileNo){
        log.error("Handler设备号离线：" + pileNo);
        if(StringUtils.isEmpty(pileNo)){
            return;
        }
        IRechargePileService iRechargePileService = SpringUtil.getBean(IRechargePileService.class);
        IRechargeGunService iRechargeGunService = SpringUtil.getBean(IRechargeGunService.class);
      //TODO 根据业务逻辑处理
        /**
        RocketMQTemplate rocketMQTemplate = SpringUtil.getBean(RocketMQTemplate.class);
        MQProperties mqProperties = SpringUtil.getBean(MQProperties.class);
        RechargePile rechargePile = iRechargePileService.getByPileNo(pileNo);
        rechargePile.setLiveStatus(BizConstant.OnOffLine.OFFLINE);
        iRechargePileService.updateById(rechargePile);
        UpdateWrapper<RechargeGun> updateWrapper = Wrappers.<RechargeGun>update();
        updateWrapper.set("online_status", BizConstant.OnOffLine.OFFLINE);
        updateWrapper.eq("pile_no", pileNo);
        iRechargeGunService.update(updateWrapper);
        //30分钟如果还没在线就判定离线，如果不在线还没在线就发送异常报告 16
        Message<String> payload = MessageBuilder.withPayload(pileNo).build();
        rocketMQTemplate.asyncSend(mqProperties.getIssueChargeRetryTopic() + ":" + BizEventTag.DEVICE_OFFLINE.name(),
                payload, RocketmqSendCallbackBuilder.commonCallback(), 3000, 16);
         *
         */

    }

}
